package components

import (
	"net"
	"net/http"
	"strings"
)

// GetLocalIp 获取本地IP
func GetLocalIp() string {
	ip, err := net.LookupIP("localhost")
	if err != nil {
		return ""
	}
	return ip[0].String()
}

// GetClientIP 获取客户端IP地址
func GetClientIP(r *http.Request) string {
	// 尝试从各种头部获取真实IP
	ip := r.Header.Get("X-Real-IP")
	if ip != "" {
		return ip
	}

	ip = r.Header.Get("X-Forwarded-For")
	if ip != "" {
		// X-Forwarded-For 可能包含多个IP，取第一个
		ips := strings.Split(ip, ",")
		if len(ips) > 0 {
			return strings.TrimSpace(ips[0])
		}
	}

	ip = r.Header.Get("X-Forwarded")
	if ip != "" {
		return ip
	}

	ip = r.Header.Get("X-Cluster-Client-IP")
	if ip != "" {
		return ip
	}

	ip = r.Header.Get("X-Client-IP")
	if ip != "" {
		return ip
	}

	// 从 RemoteAddr 获取
	if r.RemoteAddr != "" {
		ip, _, err := net.SplitHostPort(r.RemoteAddr)
		if err == nil {
			return ip
		}
		return r.RemoteAddr
	}

	return ""
}
